﻿using MediatR;
using MES.Process.API.Application.Command.工艺命令;
using MES.Process.API;
using MES.Process.Domain;
using MES.Process.ErrorCode;
using MES.Process.Infrastructure;
using Microsoft.EntityFrameworkCore;

namespace MES.Process.API.Application.CommandHandler.工艺命令处理
{
    /// <summary>
    /// 工艺命令查询处理器
    /// </summary>
    public class CraftsQueryCommandHandler : IRequestHandler<CraftsQueryCommand, APIResult<APIPaging<Crafts>>>
    {
        private readonly IBaseRepository<Crafts> craftsRepository;
        private readonly ILogger<CraftsAddCommandHandler> logger;
        public CraftsQueryCommandHandler(IBaseRepository<Crafts> craftsRepository, ILogger<CraftsAddCommandHandler> logger = null)
        {
            this.craftsRepository = craftsRepository;
            this.logger = logger;
        }

        public async Task<APIResult<APIPaging<Crafts>>> Handle(CraftsQueryCommand request, CancellationToken cancellationToken)
        {
            try
            {
                APIResult<APIPaging<Crafts>> result = new APIResult<APIPaging<Crafts>>();

                var cacheKey = $"Crafts:Page:{request.PageIndex}:{request.PageSize}";
                var cached = RedisUtil.Get<APIPaging<Crafts>>(cacheKey);
                if (cached != null && cached.List != null && cached.List.Count > 0)
                {
                    result.Code = APIEnums.Success;
                    result.Message = "获取成功";
                    result.Data = cached;
                    logger?.LogInformation("工艺列表命中缓存");
                    return result;
                }

                var query = craftsRepository.GetValues();

                int totalcount = await query.CountAsync(cancellationToken);
                int skip = (request.PageIndex - 1) * request.PageSize;
                var items = await query
                    .OrderByDescending(x => x.ID)
                    .Skip(skip)
                    .Take(request.PageSize)
                    .ToListAsync(cancellationToken);

                var totalPage = (int)Math.Ceiling(totalcount * 1.0 / request.PageSize);
                result.Code = APIEnums.Success;
                result.Message = "获取成功";
                result.Data = new APIPaging<Crafts> 
                {
                    TotalCount = totalcount,
                    TotalPages = totalPage,
                    List = items
                };

                RedisUtil.Set(cacheKey, result.Data, TimeSpan.FromMinutes(10));

                logger?.LogInformation("工艺列表获取成功");
                return result;
            }
            catch (Exception ex)
            {

                throw;
            }
        }
    }
}
